<?php
namespace app\shop\service\company;
use app\shop\model\company\EntryFile;
use app\shop\model\company\EntryFileType;
use app\shop\model\company\Staff as StaffModel;
use app\shop\model\company\StaffLeave;
use app\shop\model\company\TrainStudent;
use app\shop\model\settings\Region;
use app\shop\model\user\User;
use app\common\service\Result;
use app\shop\validate\company\Staff as StaffValidate;
class Staff
{
    public function lists($data)
    {
        try {
            $app_id = request()->app_id;
            $map = [
                ['staff.app_id', '=', $app_id]
            ];
            if (isset($data['department_id']) && $data['department_id']) {
                $map[] = ['department_id', '=', $data['department_id']];
            }
            if (isset($data['status'])) {
                $map[] = ['status', 'in', $data['status']];
            }
            if (isset($data['job_id']) && $data['job_id']) {
                $map[] = ['job_id', '=', $data['job_id']];
            }
            if (isset($data['station_id']) && $data['station_id']) {
                $map[] = ['station_id', '=', $data['station_id']];
            }
            if (isset($data['type'])) {
                $map[] = ['type', 'in', $data['type']];
            }
            if (isset($data['join_time'])) {
                $start_time = strtotime($data['join_time'][0]);
                $end_time = strtotime($data['join_time'][1] . " 23:59:59");
                $map[] = ['join_time', 'between', [$start_time, $end_time]];
            }
            $page_size = $data['page_size'] ?? 20;
            $query = StaffModel::withJoin([
                'user' => function ($q) use ($data) {
                    if (isset($data['keyword']) && $data['keyword']) {
                        $q->where('real_name|user.user_id|mobile', 'like', "%" . $data['keyword'] . "%");
                    }
                    return $q->field('user.user_id,nickName,real_name,mobile,avatarUrl');
                }
            ])->with([
                        'department' => function ($q) {
                            return $q->field('id,title');
                        },
                        'station' => function ($q) {
                            return $q->field('id,title');
                        },
                        'handleUser' => function ($q) {
                            return $q->field('user.user_id,nickName,real_name,mobile');
                        }
                    ]);
            $lists = $query->where($map)->append(['status_text', 'type_text'])->order('type desc,department_id,join_time desc')->paginate($page_size)->toArray();
            $check_train = $data['check_train'] ?? 0;
            if ($check_train == 1) {
                foreach ($lists['data'] as &$v) {
                    //是否已经加入培训班
                    $in_train = TrainStudent::find($v['user_id']);
                    $v['in_train'] = $in_train ? true : false;
                }
            }
            return Result::success($lists);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function form($user_id)
    {
        $app_id = request()->app_id;
        $info = StaffModel::where('app_id', $app_id)->withoutField(['create_time,update_time,delete_time'])
            ->find($user_id)?->bindAttr('user', ['real_name', 'mobile']);
        return Result::Success($info);
    }

    public function detail($user_id)
    {
        $app_id = request()->app_id;
        $info = StaffModel::where('app_id', $app_id)
            ->with([
                'department',
                'station'
            ])
            ->find($user_id)?->bindAttr('user', ['real_name', 'mobile', 'avatarUrl'])->bindAttr('department', ['title'])->append(['status_text', 'type_text']);
        return Result::Success($info);
    }

    //添加部门成员
    public function save($data)
    {
        try {
            $app_id = request()->app_id;
            $user = User::where('app_id', $app_id)->find($data['user_id']);
            if (!$user) {
                return Result::error('用户不存在');
            }
            if ($data['real_name']) {
                $user->real_name = $data['real_name'];
            }
            if ($data['mobile']) {
                $user->mobile = $data['mobile'];
            }
            $user->save();
            //是否已存在
            $staff = StaffModel::where('app_id', $app_id)->find($data['user_id']);
            $data['job_id'] = $data['job_id'] ?? "";
            if (isset($data['leave_time']) && $data['leave_time']) {
                $data['status'] = StaffModel::STATE_LEAVE;
            } elseif (isset($data['regular_time']) && $data['regular_time']) {
                $data['status'] = StaffModel::STATE_REGULAR;
            } else {
                $data['status'] = StaffModel::STATE_JOB;
            }
            $data['is_hostel'] = $data['is_hostel'] ?? 0;
            $data['residence_permit'] = $data['residence_permit'] ?? 0;
            $native_place = $data['native_place'] ?? [];
            if ($native_place) {
                $province = $native_place[0] ?? 0;
                $province_name = Region::withoutGlobalScope()->where('id', $province)->value('name');
                $city = $native_place[1] ?? 0;
                $city_name = Region::withoutGlobalScope()->where('id', $city)->value('name');
                $county = $native_place[2] ?? 0;
                $country_name = Region::withoutGlobalScope()->where('id', $county)->value('name');
                $data['native_place_txt'] = $province_name . $city_name . $country_name;
            }
            if ($staff) {
                if (!$staff->job_id && !$data['job_id']) {
                    $data['job_id'] = $this->getJobId($app_id);
                }
                $staff->save($data);
            } else {
                $data['app_id'] = $app_id;
                $data['status'] = 1;
                if (!$data['job_id']) {
                    $data['job_id'] = $this->getJobId($app_id);
                }
                $staff = StaffModel::create($data);
            }

            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    //删除部门成员
    public function delStaff($user_id)
    {
        try {
            $app_id = request()->app_id;
            $user = StaffModel::where('app_id', $app_id)->find($user_id);
            $user->delete();
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    //设置会员
    //type 1副经理 2经理
    public function setStaff($data)
    {
        try {
            $app_id = request()->app_id;
            validate(StaffValidate::class)->scene('set')->check($data);
            //是否已存在
            $user = StaffModel::find($data['user_id']);
            if ($user) {
                $user->department_id = $data['department_id'];
                $user->type = $data['type'];
                $user->save();
            } else {
                $data = [
                    'user_id' => $data['user_id'],
                    'department_id' => $data['department_id'],
                    'type' => $data['type'],
                    'app_id' => $app_id,
                    'join_id' => $this->getJobId($app_id),
                ];
                $user = StaffModel::create($data);
            }
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    //获取工号
    public function getJobId($app_id)
    {
        $job_id = StaffModel::where('app_id', $app_id)->max('job_id');
        if (!$job_id) {
            $job_id = 10001;
        }
        return $job_id + 1;
    }

    //入职
    public function entry($data)
    {
        try {
            $app_id = request()->app_id;
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    //离职
    public function resign($data)
    {
        try {
            $app_id = request()->app_id;
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function saveFile($data)
    {
        try {
            $app_id = request()->app_id;
            $file_type = $data['file_type'];
            $type_map = [
                'type_name' => $file_type,
                'app_id' => $app_id,
            ];
            $has_type = EntryFileType::where($type_map)->find();
            if (!$has_type) {
                EntryFileType::create($type_map);
            }
            $id = $data['id'] ?? 0;
            if ($id) {
                $file = EntryFile::find($id);
                if ($file->sign) {
                    return Result::error('用户已确认，不能修改');
                }
                $file->save($data);
            } else {
                $data['app_id'] = $app_id;
                EntryFile::create($data);
            }
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function fileTypes()
    {
        try {
            $lists = EntryFileType::where('app_id', request()->app_id)->select();
            return Result::success($lists);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function delFile($id)
    {
        try {
            $file = EntryFile::find($id);
            if (!$file) {
                return Result::error('数据不存在');
            }
            if ($file->sign) {
                return Result::error('用户已确认，不能删除');
            }
            $file->delete();
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function files($user_id)
    {
        try {
            $lists = EntryFile::where('user_id', $user_id)->with([
                'addUser' => function ($q) {
                    $q->field('user_id,avatarUrl,nickName,real_name');
                }
            ])->select();
            return Result::success($lists);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function options()
    {
        try {
            $map = [
                ['app_id', '=', request()->app_id],
                ['status', 'in', [1, 2]]
            ];
            $lists = StaffModel::where($map)->with([
                'user' => function ($query) {
                    $query->field('user_id,avatarUrl,nickName,real_name');
                }
            ])->field('user_id')->select();
            return Result::success($lists);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function leave($data)
    {
        try {
            $user_id = $data['user_id'];
            $staff = StaffModel::where('user_id', $user_id)->find();
            if (!$staff) {
                return Result::error('员工不存在');
            }
            if ($staff->status < 1) {
                return Result::error('员工已离职');
            }
            $data['leave_time'] = date("Y-m-d");
            $data['app_id'] = request()->app_id;
            $res = StaffLeave::create($data);
            if ($res) {
                $staff->save();
                return Result::success();
            } else {
                return Result::error('离职办理失败');
            }
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function signEntry($data)
    {
        try {
            $id = $data['id'] ?? 0;
            if (!$id) {
                return Result::error('参数错误');
            }
            $file = EntryFile::find($id);
            if (!$file) {
                return Result::error('数据不存在');
            }
            $user_id = $data['user_id'] ?? 0;
            if ($file->user_id != $user_id) {
                return Result::error('非法操作');
            }
            $sign = $data['sign'] ?? "";
            if (!$sign) {
                return Result::error('请填写签名');
            }
            $file->sign = $sign;
            $file->save();
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function leaveInfo($user_id)
    {
        try {
            $info = StaffLeave::where('user_id', $user_id)->with('user')->find();
            return Result::success($info);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function signLeave($data)
    {
        try {
            $user_id = $data['user_id'] ?? 0;
            if (!$user_id) {
                return Result::error('参数错误');
            }
            $staff = StaffModel::where('user_id', $user_id)->find();
            if (!$staff || $staff->status == 0) {
                return Result::error('不是在职员工');
            }
            $info = StaffLeave::where('user_id', $user_id)->with('user')->find();
            if (!$info) {
                return Result::error('没有离职信息');
            }
            $sign = $data['sign'] ?? "";
            if (!$sign) {
                return Result::error('请填写签名');
            }
            $info->sign = $sign;
            $info->save();
            $staff->status = 0;
            $staff->leave_time = $data['leave_time'];
            $staff->save();
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }
}